import PlayerModule from "../../module/PlayerModule";
import AppConfig from "../config/AppConfig";
import Context from "../context/Context";
import Utils from "../utils/Utils";
import ILocalStorage from "./ILocalStorage";
import { PLATFORM } from "../platform/Platform";
import { IModule } from "../common/Common";

//本地缓存
export default class LocalDb implements IModule {

    private source: ILocalStorage = PLATFORM;

    private cache: any;

    private sign: any;

    initialize() {
        this.sign = Context.Instance.get(PlayerModule).uid;
        this.cache = Object();
    }

    setItem(key: string | number, v: string, childKey?: string) {


        if (childKey != null) {
            let oldV = this.getJson(key) || Object();
            oldV[childKey] = v;
            this.setJson(key, oldV);
            return;
        }

        let realKey = this.normalizeKey(key);
        this.cacheItem(realKey, v);
        this.source.setItem(realKey, v);
    }

    getItem(key: string | number, childKey?: string) {
        key = this.normalizeKey(key);

        if (childKey != null) {
            let v = this.getJson(key) || Object();
            return v[childKey];
        }

        let v = this.cache[key];
        if (v) return v;

        v = this.source.getItem(key);
        this.cacheItem(key, v);
        return v;
    }

    getJson(key: string | number) {

        key = this.normalizeKey(key);
        let v = this.cache[key];
        if (v) return v;

        try {
            let item = this.source.getItem(key);
            if (!item) return null;

            let json = JSON.parse(item);
            this.cacheItem(key, json);
            return json;

        } catch (e) {
            console.log(e);
        }

    }

    setJson(key: string | number, value: object) {
        try {
            key = this.normalizeKey(key);
            this.cacheItem(key, value);
            this.source.setItem(key, JSON.stringify(value));
        } catch (e) {
            console.error(e);
        }
    }


    getItemAsNum(key: string | number, childKey?: string) {

        return Utils.parseNum(this.getItem(key, childKey));
    }


    deleteItem(key: string | number) {

        let realKey = this.normalizeKey(key);

        this.cache && Reflect.deleteProperty(this.cache, realKey);
        this.source.deleteItem(realKey);
    }

    /**
     * 外部缓存调用，重新登录清除
     * @param key 
     * @param v 
     */
    setLocalItem(key: string, v: any) {
        key = this.normalizeKey(key);
        this.cacheItem(key, v);
    }

    //临时储存字段，重登录清空
    private cacheItem(key: string, v: any) {

        if (Utils.isNil(key)) {
            return;
        }

        if (Utils.isNil(this.cache)) {
            this.cache = Object();
        }

        this.cache[key] = v;
    }

    private normalizeKey(k: string | number) {
        if (AppConfig.Debug) {

            return `${this.sign}_local_${k}`;
        }

        return `${this.sign}${k}`;
    }

}